package com.carl.guli.controller;

import com.alibaba.fastjson.JSON;
import com.carl.guli.controller.BaseController;
import com.carl.guli.dto.Result;
import com.carl.guli.model.Hotel;
import com.carl.guli.model.News;
import com.carl.guli.service.NewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by youzm on 2017/5/16.
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController{

    @Autowired
    private NewsService newsService;

    @RequestMapping("/init.do")
    public ModelAndView initNews(){
        return new ModelAndView("news");
    }

    @RequestMapping("/list.do")
    @ResponseBody
    public PageInfo<News> listFarmStay(News news) {
        PageHelper.startPage(news.getPage().getPageNum(),news.getPage().getPageSize());
        List<News> list = newsService.listNews();
        PageInfo<News> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @RequestMapping(value = "/add.do",method = RequestMethod.GET)
    public ModelAndView initNewsEdit(){
        return new ModelAndView("news_edit");
    }

    @RequestMapping(value = "/add.do",method = RequestMethod.POST)
    public String addHotel(HttpServletRequest request, News news, @RequestParam("news_pic") CommonsMultipartFile[] news_pic) throws Exception {
        newsService.addNews(news, news_pic);
        return "redirect:init.do";
    }

    @RequestMapping(value = "/edit.do",method = RequestMethod.GET)
    public ModelAndView initEditNews(ModelMap mm, Integer newsId) {
        News news = newsService.findNewsById(newsId);

        Date publishTime = news.getPublishTime();
        if (publishTime != null){
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sf.format(publishTime);
            mm.put("publishTime", format);
        }


        mm.put("news", news);

        return new ModelAndView("news_edit");
    }

    @RequestMapping(value = "/edit.do",method = RequestMethod.POST)
    @ResponseBody
    public Result editNews(News news, String oper, Integer id){
        if (oper.equals("edit")){
            newsService.editNews(news);
        }

        if (oper.equals("del")){
            newsService.delNews(id);
        }

        return new Result(1,"");
    }
}
